package com.setin.thread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ThreadHandlerActivity extends Activity {

	int mainValue = 0;
	TextView mFrontText;
	TextView mBackText;
	
	BackThread mThread;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mFrontText = (TextView) findViewById(R.id.frontText);
		mBackText = (TextView) findViewById(R.id.backText);
		Button button = (Button) findViewById(R.id.button);

		button.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				mainValue++;
				mFrontText.setText("MainValue : " + mainValue);
			}
		});
		
		Handler mHandler = new Handler(){
			public void handleMessage(Message message){
				if(message.what == 0){
					mBackText.setText("BackValue : " + message.arg1);
				}
			}
		};
		
		
		mThread = new BackThread(mHandler);
		mThread.setDaemon(true);
		mThread.start();

	}

	class BackThread extends Thread {

		int mBackValue = 0;
		Handler mHandler;

		public BackThread(Handler handler) {
			mHandler = handler;
		}

		public void run() {
			while (true) {
				mBackValue++;
				Message msg = Message.obtain(mHandler, 0, mBackValue, 0);
				mHandler.sendMessage(msg);
				
				try{
					Thread.sleep(1000);
					
				}catch(InterruptedException e){
				}
			}
		}

	}
}